<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置参数!"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            clearable
            change-on-select
            v-model="selectKey"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" type="card" @tab-click="tabhandleClick">
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showmanydialogVisible"
            >添加动态参数</el-button
          >
          <!-- 动态表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="valsClose(i,scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                ></el-button>
              </template> </el-table-column
          ></el-table>
        </el-tab-pane>
        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showmanydialogVisible"
            >添加静态属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag
                  closable
                  @close="valsClose(i,scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                ></el-button>
              </template> </el-table-column
          ></el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数 -->
    <el-dialog
      :title="'添加' + titelText"
      :visible.sync="manydialogVisible"
      width="50%"
      @close="manyhandleClose"
    >
      <el-form
        :model="manyTableDataForm"
        :rules="manyrules"
        ref="manyruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titelText" prop="attr_name">
          <el-input v-model="manyTableDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="manydialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addmanydialogVisible"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改参数 -->
    <el-dialog
      :title="'修改' + titelText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="edithandleClose"
    >
      <el-form
        :model="editTableDataForm"
        :rules="editrules"
        ref="editruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titelText" prop="attr_name">
          <el-input v-model="editTableDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editdialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectKey: [],
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      manyTableDataForm: {
        attr_name: "",
      },
      editTableDataForm: {},
      manydialogVisible: false,
      editdialogVisible: false,
      manyrules: {
        attr_name: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ],
      },
      editrules: {
        attr_name: [
          { required: true, message: "内容不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      var { data: resp } = await this.$http.get("categories");
      if (resp.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.cateList = resp.data;
    },
    handleChange() {
      this.getParamsData();
    },
    tabhandleClick() {
      this.getParamsData();
    },
    //获取参数列表数据
    async getParamsData() {
      if (this.selectKey.length !== 3) {
        this.selectKey = [];
         this.manyTableData= [];
          this.onlyTableData = [];
        return;
      }
      //根据选择的分类ID获取参数
      var { data: resp } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (resp.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      resp.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      console.log(resp.data);
      if (this.activeName == "many") {
        this.manyTableData = resp.data;
      } else {
        this.onlyTableData = resp.data;
      }
    },
    addmanydialogVisible() {
      this.$refs.manyruleForm.validate(async (val) => {
        if (!val) return;
        var { data: resp } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.manyTableDataForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (resp.meta.status !== 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.manydialogVisible = false;
        this.getParamsData();
      });
    },
    manyhandleClose() {
      this.$refs.manyruleForm.resetFields();
    },
    showmanydialogVisible() {
      this.manydialogVisible = true;
    },
    // 修改
    async editParams(attr_id) {
      this.editdialogVisible = true;
      var { data: resp } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (resp.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.editTableDataForm = resp.data;
    },
    editdialog() {
      this.$refs.editruleForm.validate(async (val) => {
        if (!val) return;
        var { data: resp } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editTableDataForm.attr_id}`,
          {
            attr_name: this.editTableDataForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (resp.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.$message.success("修改成功");
        this.editdialogVisible = false;
        this.getParamsData();
      });
    },
    edithandleClose() {
      this.$refs.editruleForm.resetFields();
    },
    async deleteParams(attr_id) {
      var con = await this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).catch((err) => err);
      if (con !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      } else {
        var { data: resp } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`,
          {
            attr_sel: this.activeName,
          }
        );
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.getParamsData();
      }
    },
    // 关闭标签
   async valsClose(i,row) {
     row.attr_vals.splice(i,1)
     var { data: resp } = await this.$http.put(
          `categories/${this.cateId}/attributes/${row.attr_id}`,
          {
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
          }
        )
         if (resp.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
       
        this.getParamsData();
    },
    async  handleInputConfirm(row) {
      if (row.inputValue.trim().length ==0) {
        row.inputVisible = false;
        row.inputValue = ' ';
        return
      }
      row.attr_vals.push(row.inputValue.trim()
      )
        row.inputVisible = false;
        row.inputValue = ' ';
        var { data: resp } = await this.$http.put(
          `categories/${this.cateId}/attributes/${row.attr_id}`,
          {
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
          }
        )
         if (resp.meta.status !== 200) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
       
        this.getParamsData();
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectKey.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {
      if (this.selectKey.length === 3) {
        return this.selectKey[2];
      }
      return null;
    },
    titelText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态绑定";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
